package org.dreamwork.jasmine2.util;

import org.dreamwork.jasmine2.javac.IClasspathBuilder;
import org.dreamwork.jasmine2.javac.JasmineCreator2;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 12-4-9
 * Time: 下午6:01
 */
public class DefaultClasspathBuilder implements IClasspathBuilder {
    private Set<URL> urls = new HashSet<URL> ();
    private boolean parsed = false;

    public String getClasspath () throws IOException {
        boolean isWindows = System.getProperty ("os.name").toLowerCase ().contains ("windows");
        Set<String> set = new HashSet<String> ();
        ClassLoader loader = getClass ().getClassLoader ();
        while (loader != null) {
            if (loader instanceof URLClassLoader) {
                URL[] us = ((URLClassLoader) loader).getURLs ();
                if (us != null) for (URL url : us) {
                    String path = url.getPath ();
                    if (path.startsWith ("file:")) path = path.substring (5);
                    if (isWindows && path.charAt (0) == '/') path = path.substring (1);
                    if (path.endsWith ("!/")) path = path.substring (0, path.length () - 2);
                    path = path.replace ("%20", " ");
                    File file = new File (path);
                    set.add (file.getCanonicalPath ());
                    urls.add (file.toURI().toURL ());
                }
            }
            loader = loader.getParent ();
        }

        JasmineCreator2.setCompileUrls (urls);

        StringBuilder builder = new StringBuilder ();
        for (String path : set) {
            if (builder.length () > 0) builder.append (File.pathSeparatorChar);
            builder.append (path);
        }

        parsed = true;
        return builder.toString ();
    }

    public Set<URL> getClasspathUrls () throws IOException {
        if (!parsed) getClasspath ();
        return urls;
    }
}
